package org.ht.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.registry.infomodel.User;

import org.apache.ibatis.annotations.Param;
import org.aspectj.apache.bcel.generic.IINC;
import org.ht.dao.CertificationDao;
import org.ht.pojo.*;
import org.ht.service.*;
import org.ht.util.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
//借款人
@Controller
@RequestMapping("brower")
public class BorrowmoneyController {
	@Autowired
	public BiaoService biaoService;
	@Autowired
	private BorrowmoneyService borrowmoneyService;
	@Autowired
	private BorrowcordService borrowcordService;

	@Autowired
	private ProductService productService;
	
	@Autowired
	private InvestService investService;
	
	@Autowired
	private CertificationService certificationService;

	@Autowired
	HttpSession session;

	@Autowired
	CertificationDao certificationDao;
	
	static final String str = "WEB-INF/view/";

	@RequestMapping("qurey")
	public String allMoney(HttpServletRequest request, Borrowmoney borrowmoney, Model model,
			@RequestParam(value = "currpage", required = false) String currpage) {
		final int pagerow = 5;// 每页5行
		int currpages = 1;// 当前页
		int totalpage = 0;// 总页数
		int totalrow = 0;// 总行数
		Borrowmoney borrowmoney1 = new Borrowmoney();
		borrowmoney1.setBtype(borrowmoney.getBtype());
		borrowmoney1.setBstate(borrowmoney.getBstate());
		borrowmoney1.setBusername(borrowmoney.getBusername());

		if (borrowmoney.getBtype() == null || borrowmoney.getBtype().equals("")
				|| borrowmoney.getBtype().equals("请选择")) {

			borrowmoney1.setBtype(null);
		}
		if (borrowmoney.getBstate() == null || borrowmoney.equals("") || borrowmoney.getBstate().equals("请选择")) {

			borrowmoney1.setBstate(null);
		}
		List<Borrowmoney> list = borrowmoneyService.findList(BeanUtils.toMap(borrowmoney1));
		totalrow = list.size();// 获取总行数
		if (currpage != null && !"".equals(currpage)) {
			currpages = Integer.parseInt(currpage);
		}
		totalpage = (totalrow + pagerow - 1) / pagerow;
		if (currpages < 1) {
			currpages = 1;
		}
		if (currpages > totalpage) {
			if (totalpage < 1) {
				totalpage = 1;
			}
			currpages = totalpage;
		}
		Integer startPage = (currpages - 1) * pagerow;
		borrowmoney1.setStartPage(startPage);
		borrowmoney1.setPageSize(pagerow);
		List<Borrowmoney> list2 = borrowmoneyService.findList(BeanUtils.toMap(borrowmoney1));
		model.addAttribute("list", list2);
		model.addAttribute("totalrow", totalrow);
		model.addAttribute("currpages", currpages);
		model.addAttribute("totalpage", totalpage);
		List<Biao> bList = biaoService.findList(BeanUtils.toMap(new Biao()));

		model.addAttribute("page", list2);
		model.addAttribute("bList", bList);

		return str + "bk_moneylist";
	}

	@RequestMapping("audit")
	public String audit(Model model, @RequestParam(value = "currpage", required = false) String currpage,
			@RequestParam(value = "id", required = false) String id,
			@RequestParam(value = "status", required = true) String status) {
		Borrowmoney borrowmoney = new Borrowmoney();
		// 通过
		if (status.equals("1")) {
			borrowmoney.setBstate("1");
		}
		// 不通过
		if (status.equals("0")) {
			borrowmoney.setBstate("2");
		}
		borrowmoney.setId(Integer.parseInt(id));
		borrowmoneyService.update(borrowmoney);

		final int pagerow = 5;// 每页5行
		int currpages = 1;// 当前页
		int totalpage = 0;// 总页数
		int totalrow = 0;// 总行数
		borrowmoney.setBstate("0");   //状态(0:提交申请未处理;1,后台审核通过(未还款);2审核失败;3.已还款)
		List<Borrowmoney> list = borrowmoneyService.findList(BeanUtils.toMap(borrowmoney));
		totalrow = list.size();// 获取总行数
		if (currpage != null && !"".equals(currpage)) {
			currpages = Integer.parseInt(currpage);
		}
		totalpage = (totalrow + pagerow - 1) / pagerow;
		if (currpages < 1) {
			currpages = 1;
		}
		if (currpages > totalpage) {
			if (totalpage < 1) {
				totalpage = 1;
			}
			currpages = totalpage;
		}
		Integer startPage = (currpages - 1) * pagerow;
		borrowmoney.setStartPage(startPage);
		borrowmoney.setPageSize(pagerow);
		List<Borrowmoney> list2 = borrowmoneyService.findList(BeanUtils.toMap(borrowmoney));
		model.addAttribute("page", list2);
		model.addAttribute("totalrow", totalrow);
		model.addAttribute("currpages", currpages);
		model.addAttribute("totalpage", totalpage);

		return str + "bk_money_check";
	}

	@RequestMapping(value = "check")
	public String check(Borrowmoney borrowmoney, Model model,
			@RequestParam(value = "currpage", required = false) String currpage) {
		final int pagerow = 5;// 每页5行
		int currpages = 1;// 当前页
		int totalpage = 0;// 总页数
		int totalrow = 0;// 总行数
		Borrowmoney borrowmoney1 = new Borrowmoney();
		borrowmoney1.setBstate("0");
		List<Borrowmoney> list = borrowmoneyService.findList(BeanUtils.toMap(borrowmoney1));
		totalrow = list.size();// 获取总行数
		if (currpage != null && !"".equals(currpage)) {
			currpages = Integer.parseInt(currpage);
		}
		totalpage = (totalrow + pagerow - 1) / pagerow;
		if (currpages < 1) {
			currpages = 1;
		}
		if (currpages > totalpage) {
			if (totalpage < 1) {
				totalpage = 1;
			}
			currpages = totalpage;
		}
		Integer startPage = (currpages - 1) * pagerow;
		borrowmoney1.setStartPage(startPage);
		borrowmoney1.setPageSize(pagerow);
		List<Borrowmoney> list2 = borrowmoneyService.findList(BeanUtils.toMap(borrowmoney1));

		model.addAttribute("page", list2);
		model.addAttribute("totalrow", totalrow);
		model.addAttribute("currpages", currpages);
		model.addAttribute("totalpage", totalpage);

		return str + "bk_money_check";

	}

	@RequestMapping("find")
	public String find(Model model, @Param(value = "id") String id) {
		if (id == null || id.equals("")) {
			id = 1 + "";
		}
		Integer ia = Integer.parseInt(id);
		Borrowmoney mBorrowmoney = borrowmoneyService.get(ia);
		model.addAttribute("domain", mBorrowmoney);
		return str + "bk_money_detail";
	}

	//json添加还款(前台)
	@RequestMapping("toaddborr")
	@ResponseBody
	public String toadd(Borrowmoney borrowmoney) {
		Users users=(Users) session.getAttribute("globaluser");
		borrowmoney.setUserId(users.getUid());
		borrowmoney.setBstate("0");
		borrowmoneyService.toaddborr(borrowmoney);
		return "";
	}

	//还款(查询所有需要还款的还款)
	@RequestMapping("tohk")
	public String updhuankuan(Model model) {
		System.out.println(borrowmoneyService.updhuankuan().size() + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		model.addAttribute("list", borrowmoneyService.updhuankuan());

		return str + "bk_huankuanlist";
	}

	// 去查看还款详情页面
	@RequestMapping("tohuankuanupd")
	public String tohuankuan(Model model, @RequestParam(value = "id") Integer ids) {
		Borrowmoney borr = borrowmoneyService.get(ids);
		model.addAttribute("borr", borr);
		model.addAttribute("list", borrowcordService.selborr(ids));

		return str + "bk_huankuanupdeta";
	}

	//修改还款状态ids === boid   
	@RequestMapping("tohuankuanupds")
	@ResponseBody
	public String tohuankuanupd(Model model, @RequestParam(value = "ids") Integer ids,
			@RequestParam(value = "id") Integer id , @RequestParam(value="money") double money) {
		
		
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>修改还款状态");
		Borrowcord borrowcord = borrowcordService.selectByBoid(ids);
		String productId = borrowcord.getProductId();
		int bmid = Integer.parseInt(productId);
		Integer userId = borrowcord.getUserId();
		Certification c= certificationDao.select(userId);  //查询借款人账户
		c.setCpaid(c.getCpaid()- money);
		if (c.getCbalance() - money < 0) {
			return "0";
		}
		c.setCbalance(c.getCbalance() - money);
		certificationDao.update(c);
		Borrowmoney borrowmoney = borrowmoneyService.selectByPrimarykey(id);
		String btimelimit = borrowmoney.getBtimelimit();
		int month = Integer.valueOf(btimelimit);
		Map<String, Object> parameters = new HashMap<String, Object>();// 查询条件
		parameters.put("bid", bmid);
		List<InvestInfo> page = investService.investS(parameters);// 查出投资该项目的人
		//InvestInfo [inid=7, userid=3, brrowid=1, inmoney=12321.00, instatus=0, instyle=钱宝宝, brrowstatus=筹集中, interest=12.00%, profitmodel=等额本金, profitmoney=0.00, indate=2017-02-27 20:14:42.0, replaydate=无期限, markstatus=0]
		for (InvestInfo investInfo : page) {
			int userid = investInfo.getUserid();
			Certification certification = certificationService.select(userid);
			if (certification != null) {
				BigDecimal inmoney = investInfo.getInmoney();
				double profit = Double.parseDouble(investInfo.getInterest()) / 100.0 * inmoney.doubleValue() / month;
//				double profit = certification.getCdue() / 12;
				//增加投资收益
				certification.setCprofit(profit + certification.getCprofit());
				//增加余额
				certification.setCbalance(certification.getCbalance() + certification.getCprofit());
				//减少待收本息
				certification.setCdue(certification.getCdue() - profit);
				certificationService.update(certification);
			}
		}
		
		borrowcordService.updborr(ids);
		
		return "1";
		//return "redirect:tohuankuanupd.do?id=" + id;
	}

	// json
	@RequestMapping("tohuankuanupdison")
	@ResponseBody
	public List<Borrowcord> tohuankuanjson(@RequestParam(value = "id") Integer ids) {
		List<Borrowcord> list = borrowcordService.selborr(ids);
		return list;
	}

	// 点击同意时进入借款信息确认见面
	@RequestMapping("borqr")
	public String borqr(Model model, @RequestParam(value = "ids") Integer ids) {
		Borrowmoney borro = borrowmoneyService.borrowget(ids);
		model.addAttribute("borr", borro);
		return str + "bk_huankuanget";
	}

	// 点击同意时进入借款信息确认见面 (去修改)
	@RequestMapping("borxg")
	public String borxg(Model model ,@RequestParam(value = "ids")Integer ids,@RequestParam(value = "id")Integer id, Borrowmoney borrowmoney) {
		//修改状态
		borrowmoney.setBstate("1");
		borrowmoney.setId(ids);
		borrowmoneyService.update(borrowmoney);
		//增加该用户的待还金额
		Certification certification=certificationDao.select(borrowmoney.getUserId());
		double money = certification.getCpaid();
		double borMoney=Double.valueOf(borrowmoney.getBmoney().trim());
		money += borMoney;
		certification.setCpaid(money + money / 100.0 * Double.parseDouble(borrowmoney.getBrate()));
		certificationDao.update(certification);


		//同时插入product数据
		Product product=new Product();
		//设置已投资金额
		product.setPmoney(0);
		product.setPincome(borrowmoney.getBrate());
		Date date=new Date();
		Calendar calendar = Calendar.getInstance();// 时间转换
		calendar.setTime(date);
		calendar.add(Calendar.SECOND,  60 * 60 * 24 * 30);//设置标投放的时间
		date = calendar.getTime();
		product.setPtime(date);
		product.setPtype(6);
		product.setPway(borrowmoney.getBserial());
		date=new Date();
		calendar.setTime(date);
		calendar.add(Calendar.SECOND,  60 * 60 * 24 * 30*Integer.valueOf(borrowmoney.getBtimelimit().trim()));//设置标投放的时间
		date = calendar.getTime();
		product.setPcount(date);
		product.setProgress("0");
		if(borrowmoney.getBserial().equals("1"))
		{
			product.setPway("到期一次性还清本息");
		}
		else
		{
			if(borrowmoney.getBserial().equals("2")){
				product.setPway("按月付息，到期还本");
			}
			else {
				product.setPway("按月支付，每月等额");
			}
		}
		product.setPrateben(String.valueOf(Integer.valueOf(borrowmoney.getBtimelimit().trim())*Integer.valueOf(borrowmoney.getBmoney().trim())*Integer.valueOf(borrowmoney.getBrate().trim())));
		product.setPpublishtime(date);
		String tmp="";
		if(borrowmoney.getBleixing()==0){
			//车贷
			tmp+=borrowmoney.getBrelname();
			tmp+=borrowmoney.getBeizhu1();
			tmp+=borrowmoney.getBeizhu2();
			tmp+="质押";
		}
		else {
			//房贷
			tmp+=borrowmoney.getBrelname();
			tmp+="面积为";
			tmp+=borrowmoney.getBeizhu1();
			tmp+=",房龄";
			tmp+=borrowmoney.getBeizhu2();
			tmp+="质押";
		}
		product.setPname(tmp);
//		product.setPtotalmoney(Integer.valueOf(borrowmoney.getBmoney().trim())+Double.valueOf(product.getPrateben().trim()));
		product.setPtotalmoney(Double.valueOf(borrowmoney.getBmoney()));
		product.setPrange("50元~ 不限");
		product.setPuse("临时周转");
		product.setPstate("1");
		product.setPicture("/p2p/cover/1.jpg");
		product.setPproduce(1);
//		product.setPdesc();
		productService.create(product);

		//处理还款记录表,对borrowcord进行插入
		borrowcordService.borradd(product.getId(),borrowmoney.getBtimelimit(), borrowmoney.getId(), borrowmoney.getBserial(), borrowmoney.getUserId());

		return "redirect:check.do";
	}

	// hjy
	@RequestMapping("hjyList")
	public String hjyList(Model m, @RequestParam(value = "currpage", required = false) String currpage) {
		Map<String, Object> wmap = borrowmoneyService.selecthjy(currpage);
		List<Borrowmoney> llist = (List<Borrowmoney>) wmap.get("llist");
		m.addAttribute("pagerow", wmap.get("pagerow"));
		m.addAttribute("currpages", wmap.get("currpages"));
		m.addAttribute("wdlist", llist);
		m.addAttribute("totalpage", wmap.get("totalpage"));
		m.addAttribute("totalrow", wmap.get("totalrow"));
		return str + "Borrowmoneylist";
	}

	// hjy
	@RequestMapping("bajax")
	@ResponseBody
	public Borrowmoney ajax(@RequestParam(value = "id", required = false) int id) {
		System.out.println(id);
		System.out.println(borrowmoneyService.get(id).getBrelname());
		return borrowmoneyService.get(id);
	}

}
